﻿using Exam.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Exam.BLL;
using Exam.DBHelper;
using System.Data.SqlClient;
using ExaminationWeb.Common;
namespace ExaminationWeb.Controllers
{
    public class RoleController : Controller
    {
        //
        // GET: /Role/
        RoleService roleservice = new RoleService();
        RoleMenuService rolemenuService = new RoleMenuService();
        public ActionResult RoleList()
        {
            return View();
        }
        public ActionResult RoleAdd()
        {
            return View();
        }

        public ActionResult RoleUpdate(string id)
        {
            Guid guid = Guid.Parse(id);
            string menuidlist = string.Join("|", rolemenuService.LoadEntites(e => e.RoleID == guid).Select(e => e.MenuID));
            ViewData["Menu"] = menuidlist;
            Role role = roleservice.LoadEntites(m => m.RoleID == guid).First();
            ViewData["Role"] = role;
            return View();
        }

        #region 数据请求

        [AllowAnonymous]
        public JsonResult RoleList_GetData()
        {
            int pageIndex = Request["sEcho"] == null ? 1 : int.Parse(Request["sEcho"]);
            int pageSize = Request["iDisplayLength"] == null ? 15 : int.Parse(Request["iDisplayLength"]);
            int pageStart = Request["iDisplayStart"] == null ? 0 : int.Parse(Request["iDisplayStart"]);

            string SortDirindex = Request["iSortCol_0"] == null ? "" : Request["iSortCol_0"];
            string SortDir = "";
            string DataProp = "";
            if (!string.IsNullOrEmpty(SortDirindex))
            {
                DataProp = Request["mDataProp_" + SortDirindex] == null ? "" : Request["mDataProp_" + SortDirindex];
                SortDir = Request["sSortDir_0"] == null ? "" : Request["sSortDir_0"]; //asc or desc
            }
            int totalcount = 0;
            string Rolename = Request["Rolename"] == null ? "" : Request["Rolename"];
            string isdelete = Request["isactive"] == null ? "-1" : Request["isactive"];
            IQueryable<Role> data;
            if (isdelete == "-1")
            {
                if (string.IsNullOrEmpty(Rolename))
                {
                    data = roleservice.LoadEntites(e => true, DataProp, SortDir == "asc", pageStart, pageSize, out totalcount);
                }
                else
                {
                    data = roleservice.LoadEntites(e => e.RoleName.ToLower().Contains(Rolename.ToLower()), DataProp, SortDir == "asc", pageStart, pageSize, out totalcount);
                }
            }
            else
            {
                if (string.IsNullOrEmpty(Rolename))
                {
                    //  data = toolListService.LoadEntites(e => e.State == 0 , pageStart, pageSize, out totalcount);
                    data = roleservice.LoadEntites(e => e.IsActive == int.Parse(isdelete), DataProp, SortDir == "asc", pageStart, pageSize, out totalcount);
                }
                else
                {
                    data = roleservice.LoadEntites(e => e.IsActive == int.Parse(isdelete) && e.RoleName.ToLower().Contains(Rolename.ToLower()), DataProp, SortDir == "asc", pageStart, pageSize, out totalcount);
                }
            }
            var result = new { iTotalDisplayRecords = totalcount, iTotalRecords = totalcount, aaData = data, sEcho = 0 };

            return Json(result, JsonRequestBehavior.AllowGet);
        }
        [AllowAnonymous]
        public string Addinfo(Role role, string[] PagesCheck)
        {
            try
            {
                if (IsExistData(role).RoleID.ToString() == "00000000-0000-0000-0000-000000000000")
                {
                    role.RoleID = Guid.NewGuid();
                    DateTime time = DateTime.Now;
                    role.CreateTime = time;
                    role.UpdateTime = time;
                    role.CreateUserID = UserAccount.UserID;
                    role = roleservice.AddEntity(role);

                    //添加角色和页面的关系表数据
                    if (PagesCheck != null)
                    {
                        foreach (string menu in PagesCheck)
                        {
                            RoleMenu rp = new RoleMenu()
                            {
                                RoleMenuID = Guid.NewGuid(),
                                RoleID = role.RoleID,
                                MenuID = Guid.Parse(menu),
                                CreateTime = DateTime.Now,
                                CreateUser = UserAccount.UserID
                            };
                            rolemenuService.AddEntity(rp);
                        }
                    }
                    return "suc";
                }
                else
                {
                    return "repeat";
                }

            }
            catch (Exception e)
            {
                return "err";
            }
        }
        [AllowAnonymous]
        public string Updateinfo(Role role, string[] PagesCheck)
        {

            try
            {
                Role _role = IsExistData(role);
                if (_role.RoleID.ToString() == "00000000-0000-0000-0000-000000000000" || _role.RoleID == role.RoleID)
                {
                    role.UpdateTime = DateTime.Now;
                    role.UpdateUserID = UserAccount.UserID;
                    role = roleservice.UpdateEntity(role);

                    //添加角色和页面的关系表数据
                    rolemenuService.DelEntityByWhere(m => m.RoleID == role.RoleID);

                    if (PagesCheck != null)
                    {
                        foreach (string menu in PagesCheck)
                        {
                            RoleMenu rp = new RoleMenu()
                            {
                                RoleMenuID = Guid.NewGuid(),
                                RoleID = role.RoleID,
                                MenuID = Guid.Parse(menu),
                                CreateTime = DateTime.Now,
                                CreateUser = UserAccount.UserID
                            };
                            rolemenuService.AddEntity(rp);
                        }
                    }
                    //如果修改的是当前登录人的权限，则重置Session["LoginUserRoles"]和Session["LoginUserRolePages"]
                    //                    if (LoginUserRoles().Exists(m => m.RoleID == role.RoleID))
                    //                    {
                    //                        List<Role> listUserRoles = commonService.GetEntities<Role>(@"select r.* from User_Role ur
                    //                                            left join Role r on r.RoleID=ur.RoleID
                    //                                            where ur.UserID='" + LoginUserID() + "'");
                    //                        Session["LoginUserRoles"] = listUserRoles;
                    //                        List<Page> LoginUserRolePages = commonService.GetEntities<Page>(@"select p.* from Page p 
                    //                                            left join Role_Page rp on p.PageID=rp.PageID
                    //                                            left join User_Role ur on ur.RoleID=rp.RoleID
                    //                                            where ur.UserID='" + LoginUserID() + @"'");
                    //                        Session["LoginUserRolePages"] = LoginUserRolePages;
                    //                    }
                    return "suc";
                }
                else
                {
                    return "repeat";
                }
            }
            catch (Exception e)
            {
                return "err";
            }
        }
        #endregion

        #region 公用
        public Role IsExistData(Role Role)
        {
            SQLHelper commonservice = new SQLHelper();
            Dictionary<string, SqlParameter> dic = new Dictionary<string, SqlParameter>();

            SqlParameter parname = new SqlParameter("@RoleName", System.Data.SqlDbType.NVarChar);
            parname.Value = Role.RoleName;
            dic.Add("RoleName", parname);
            return commonservice.getExistData<Role>("Role", dic);
        }
        #endregion
    }
}
